final

Author

최규빈

Published

December 18, 2022

기말고사

주의: 엑셀 등을 이용하여 자료를 전처리할 경우 부분점수 없이 0점 처리함

import pandas as pd 
import json 
import requests 
import folium 
import plotly.express as px

1. 시군구별 에너지사용량 시각화 (30점)

아래의 주소들에서 2018-2021의 시군구별 에너지 사용량에 대한 자료를 정리하고 물음에 답하라.

# 2018
https://raw.githubusercontent.com/guebin/DV2022/main/posts/Energy/Seoul2018.csv
...
https://raw.githubusercontent.com/guebin/DV2022/main/posts/Energy/Jeju-do2018.csv

# 2019
https://raw.githubusercontent.com/guebin/DV2022/main/posts/Energy/Seoul2019.csv
...
https://raw.githubusercontent.com/guebin/DV2022/main/posts/Energy/Jeju-do2019.csv

# 2020
https://raw.githubusercontent.com/guebin/DV2022/main/posts/Energy/Seoul2020.csv
...
https://raw.githubusercontent.com/guebin/DV2022/main/posts/Energy/Jeju-do2020.csv

# 2021
https://raw.githubusercontent.com/guebin/DV2022/main/posts/Energy/Seoul2021.csv
...
https://raw.githubusercontent.com/guebin/DV2022/main/posts/Energy/Jeju-do2021.csv

hint1: 코드1, 코드2를 적절하게 응용하면 쉽게 데이터를 합칠 수 있음

## 코드1 
_district = [global_dict['features'][i]['properties']['name_eng'] for i in range(17)]
_year = ['2018','2019','2020','2021']
for d in _district:
    for y in _year: 
        print(d+y)
        
## 코드2
_url = 'https://raw.githubusercontent.com/guebin/DV2022/main/posts/Energy/{}.csv' 
pd.concat([pd.read_csv(_url.format(k)) for k in ['Seoul2018','Jeju-do2018']])

hint2: 데이터프레임을 읽었을 때 ['에너지사용량(TOE)/지역난방']의 자료형이 통일되어 있지 않음을 유의하여 처리할 것.

pd.read_csv('https://raw.githubusercontent.com/guebin/DV2022/main/posts/Energy/Gangwon-do2021.csv')['에너지사용량(TOE)/지역난방'].dtype
dtype('int64')
pd.read_csv('https://raw.githubusercontent.com/guebin/DV2022/main/posts/Energy/Seoul2021.csv')['에너지사용량(TOE)/지역난방'].dtype
dtype('O')

hint3: 아래의 코드를 이용하여 geojson 파일을 확보하고 문제를 풀 것

global_dict = json.loads(requests.get('https://raw.githubusercontent.com/southkorea/southkorea-maps/master/kostat/2018/json/skorea-provinces-2018-geo.json').text)
local_dict = json.loads(requests.get('https://raw.githubusercontent.com/southkorea/southkorea-maps/master/kostat/2018/json/skorea-municipalities-2018-geo.json').text)

hint4: 필요하다면 아래의 코드를 활용할 것 (활용하지 않아도 무방함)

_df = pd.DataFrame({'A':['서초구','강남구','송파구'],'B':['33,231','22,321',45123]})
_df                   
A B
0 서초구 33,231
1 강남구 22,321
2 송파구 45123

(할당)

_df.assign(C=2018,D='Seoul')
A B C D
0 서초구 33,231 2018 Seoul
1 강남구 22.321 2018 Seoul
2 송파구 45123 2018 Seoul

(인덱스)

_df.assign(C=2018,D='Seoul').set_index(['A','D'])
B C
A D
서초구 Seoul 33,231 2018
강남구 Seoul 22.321 2018
송파구 Seoul 45123 2018

(applymap)

_df.assign(C=2018,D='Seoul').set_index(['A','D']).applymap(lambda x: int(str(x).replace(',','')))
B C
A D
서초구 Seoul 33231 2018
강남구 Seoul 22321 2018
송파구 Seoul 45123 2018

(1) 아래의 지역에 대한 4년간 전기 에너지 사용량의 총합을 구하고 folium을 이용하여 시각화 하라.

[global_dict['features'][i]['properties']['name_eng'] for i in range(17)]
['Seoul',
 'Busan',
 'Daegu',
 'Incheon',
 'Gwangju',
 'Daejeon',
 'Ulsan',
 'Sejongsi',
 'Gyeonggi-do',
 'Gangwon-do',
 'Chungcheongbuk-do',
 'Chungcheongnam-do',
 'Jeollabuk-do',
 'Jeollanam-do',
 'Gyeongsangbuk-do',
 'Gyeongsangnam-do',
 'Jeju-do']
# 시각화예시
Make this Notebook Trusted to load map: File -> Trust Notebook
  • location = [36,128], zoom_start=7 로 설정

(2) 서울의 4년간 전기에너지 사용량의 총합을 구하고 folium을 이용하여 구별로 시각화 하라.

hint 아래의 리스트에서

[local_dict['features'][i]['properties']['code'] for i in range(250)]

11로 시작하는 원소들이 서울지역이다.

# 시각화예시
Make this Notebook Trusted to load map: File -> Trust Notebook
  • location = [37.55,127], zoom_start=11 로 설정

(3) 서울의 전기에너지 사용비율을 (연도별,구별)로 구하고 이를 plotly의 choropleth_mapbox를 이용하여 시각화 하라. (연도에 따라 choropleth map이 바뀌도록 시각화 할 것)

hint1: 2020년의 관악구의 전기에너지 사용비율은 아래와 같이 계산한다.

\(\frac{\text{2020관악구의 ``에너지사용량(TOE)/전기''}}{\text{2020관악구의 ``에너지사용량(TOE)/전기''}+\text{2020관악구의 ``에너지사용량(TOE)/도시가스''}+\text{2020년 관악구의 ``에너지사용량(TOE)/지역난방''}}\)

# 시각화예시

hint2: 아래의 코드 참고할 것.

fig = px.choropleth_mapbox(data_frame=???,
                           geojson=???, 
                           color=???,
                           locations=???, 
                           featureidkey=???, 
                           center={"lat": 37.55, "lon": 126.95}, 
                           mapbox_style="carto-positron", 
                           animation_frame=???, # 2028,2019,2020,2021와 같이 년도가 명시된 column의 이름을 쓸 것
                           range_color=[0.31,0.56],
                           height=800,
                           zoom=10)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})